/**
 * Copyright (C), 2015-2018, 成都启迪信息技术有限公司
 * FileName: HttpUtil
 * Author:   sjkyll
 * Date:     2018-12-04 10:31
 * Description:
 * <author>          <time>          <version>          <desc>
 * 作者姓名         修改时间           版本号            描述
 */
package com.cdqidi.smsservice.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

/**
 * 〈一句话功能简述〉<br> 
 *
 * @author sjkyll
 * @create 2018-12-04 10:31
 * @since 1.0.0
 */
@Component
public class HttpUtil {
    @Autowired
    private CloseableHttpClient client;

    public String sendPost(String url, List<BasicNameValuePair> list, boolean isJosn) throws IOException {
        String responseJson;
        try {
            HttpPost post = new HttpPost(url);
            try {
                post.setHeader("Connection", "Keep-Alive");
                if(isJosn){
                    post.setHeader("ContentType", "application/json");
                }else{
                    post.setHeader("ContentType", "aapplication/x-www-form-urlencoded");
                }
                RequestConfig requestConfig = RequestConfig.custom()
                        .setConnectTimeout(10000).setConnectionRequestTimeout(5000)
                        .setSocketTimeout(10000).build();
                post.setConfig(requestConfig);
                HttpEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
                try {
                    post.setEntity(entity);
                    HttpResponse response = client.execute(post);
                    HttpEntity resEntity = response.getEntity();
                    try {
                        responseJson = EntityUtils.toString(resEntity);
                    } finally {
                        EntityUtils.consume(resEntity);
                    }
                } finally {
                    EntityUtils.consume(entity);
                }
            } finally {
                post.releaseConnection();
            }
        } catch (IOException e) {
            throw new IOException(e);
        }
        return responseJson;
    }
}